const COS = require('./cos-wx-sdk-v5.js')
import dayjs from 'dayjs'
import { getRandom } from '@/utils'
import store from '@/store'

// const cosConfig = {
//   Bucket: 'dev-1258219436',
//   Region: 'ap-nanjing'
// }

const getCosConfig = () => {
  return {
    Bucket: store.getters.siteInfo.bucket,
    Region: store.getters.siteInfo.region,
    pre_path: store.getters.siteInfo.pre_path
  }
}

export const cos = new COS({
  // getAuthorization: function (options, callback) {
  //   api.cosSts().then((data) => {
  //     callback({
  //       TmpSecretId: data.credentials && data.credentials.tmpSecretId,
  //       TmpSecretKey: data.credentials && data.credentials.tmpSecretKey,
  //       XCosSecurityToken: data.credentials && data.credentials.sessionToken,
  //       ExpiredTime: data.expiredTime
  //     })
  //   })
  // }
})

//获取url
export const getObjectUrl: (key: string) => Promise<string> = (key) => {
  return new Promise((resolve, reject) => {
    const cosConfig = getCosConfig()
    cos.getObjectUrl(
      {
        Bucket: cosConfig.Bucket,
        Region: cosConfig.Region,
        Key: key,
        Sign: true /* 获取不带签名的对象URL */
      },
      (err, data) => {
        if (err) {
          reject(err)
        } else {
          console.log(data, 'data')
          resolve(data.Url)
        }
      }
    )
  })
}

type CosUploadQuery = {
  key?: string
  filePath: string
  fileSize?: number
}
export const cosUploadFile = (
  query: CosUploadQuery,
  fn?: (progress) => void,
  taskFn?: (taskId) => void
) => {
  return new Promise((resolve, reject) => {
    const cosConfig = getCosConfig()
    console.log(query, 'query')
    const currentKey =
      query.key || getCosName(query.filePath.split('/').slice(-1)[0] || '')
    cos.uploadFile({
      Bucket: cosConfig.Bucket,
      Region: cosConfig.Region,
      Key: currentKey,
      FilePath: query.filePath,
      FileSize: query.fileSize,
      SliceSize: 1024 * 1024 * 5,
      onTaskReady: (taskId) => {
        //
        console.log(taskId, 'taskId')
        taskFn && taskFn(taskId)
      },
      onProgress: (progressData) => {
        console.log(progressData, 'progressData;')
        fn && fn(progressData)
        //
      },
      onFileFinish: (err, data, options) => {
        console.log(options.Key + 'cos上传' + (err ? '失败' : '完成'))
        if (err) {
          reject(err)
        } else {
          resolve(options.Key)
        }
      }
    })
  }) as Promise<string>
}

const cosFix = 'zm-cos-'

export const getCosName = (name) => {
  const cosConfig = getCosConfig()
  const pre_path = cosConfig.pre_path || ''
  return (
    pre_path + dayjs().format('YYYY-MM-DD') + '/' + cosFix + getRandom() + name
  )
}

export const isCosUrl = (name = '') => {
  if (/^(http|https)/.test(name)) {
    return false
  }
  const names = name.split('/')
  return names.some((i) => i.startsWith(cosFix))
}

export const getCosUrls = async (urls: any[], key?: string) => {
  const currentUrl = [] as string[]
  for (let i = 0; i < urls.length; i++) {
    const item = urls[i]
    const url = key ? item[key] : item
    let currentItem = '' as any
    if (isCosUrl(url)) {
      const res = await getObjectUrl(url)

      if (key) {
        currentItem = { ...item, [key]: res }
      } else {
        currentItem = res
      }
    } else {
      currentItem = item
    }
    currentUrl.push(currentItem)
  }
  return currentUrl
}
